<template>
  <view class="chat-page">
    <!-- 自定义导航栏 -->
    <nav-bar :title="chatUser.userName || '聊天'" :show-back="true"></nav-bar>
    
    <!-- 聊天主体区域 -->
    <scroll-view 
      class="chat-container"
      scroll-y
      :scroll-into-view="'msg-' + scrollToMessageId"
      scroll-with-animation
      @scrolltoupper="loadMoreMessages"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 加载更多提示 -->
      <view class="loading-more" v-if="hasMoreMessages">
        <tn-loading mode="circle" size="24"></tn-loading>
        <text>加载更多消息...</text>
      </view>
      
      <!-- 消息列表 -->
      <view class="messages">
        <block v-for="(message, index) in messages" :key="message.id">
          <!-- 日期分隔线 -->
          <view class="date-divider" v-if="shouldShowDateDivider(message, index)">
            <text>{{ formatMessageDate(message.createTime) }}</text>
          </view>
          
          <!-- 消息气泡 -->
          <view 
            :id="'msg-' + message.id"
            class="message-item"
            :class="{ 'message-self': message.isSelf }"
          >
            <!-- 头像 -->
            <image 
              class="avatar"
              :class="{ 'self-avatar': message.isSelf }"
              :src="message.userAvatar"
              mode="aspectFill"
            ></image>
            
            <!-- 消息内容 -->
            <view class="message-content" :class="{ 'self-content': message.isSelf }">
              <!-- 文本消息 -->
              <view 
                v-if="message.contentType === 'text'"
                class="message-bubble"
                :class="{ 'self-bubble': message.isSelf }"
              >
                <text>{{ message.content }}</text>
              </view>
              
              <!-- 图片消息 -->
              <view 
                v-else-if="message.contentType === 'image'"
                class="image-message"
                :class="{ 'self-image': message.isSelf }"
                @click="previewImage(message.content)"
              >
                <image 
                  class="message-image" 
                  :src="message.content" 
                  mode="widthFix"
                ></image>
              </view>
              
              <!-- 语音消息 -->
              <view 
                v-else-if="message.contentType === 'audio'"
                class="audio-message"
                :class="{ 'self-audio': message.isSelf }"
                @click="playAudio(message.content)"
              >
                <tn-icon name="voice" size="32" :color="message.isSelf ? '#ffffff' : '#333333'"></tn-icon>
                <text>{{ message.duration || '0"' }}</text>
              </view>
              
              <!-- 其他类型消息 -->
              <view 
                v-else
                class="message-bubble"
                :class="{ 'self-bubble': message.isSelf }"
              >
                <text>[不支持的消息类型]</text>
              </view>
              
              <!-- 发送状态 -->
              <view class="message-status" v-if="message.isSelf">
                <tn-icon 
                  v-if="message.status === 'sending'"
                  name="loading" 
                  size="24" 
                  color="#999999"
                ></tn-icon>
                <tn-icon 
                  v-else-if="message.status === 'failed'"
                  name="error" 
                  size="24" 
                  color="#FF5252"
                  @click="resendMessage(message)"
                ></tn-icon>
              </view>
            </view>
          </view>
        </block>
      </view>
    </scroll-view>
    
    <!-- 输入区域 -->
    <view class="input-area">
      <!-- 语音/输入切换 -->
      <view class="toggle-btn" @click="switchInputMode">
        <tn-icon :name="isTextMode ? 'voice' : 'keyboard'" size="32" color="#666666"></tn-icon>
      </view>
      
      <!-- 文本输入框 -->
      <input 
        v-if="isTextMode"
        class="text-input"
        type="text"
        v-model="inputText"
        placeholder="请输入消息..."
        confirm-type="send"
        @confirm="sendTextMessage"
        cursor-spacing="10"
      />
      
      <!-- 语音输入按钮 -->
      <view 
        v-else
        class="voice-input"
        @touchstart="startRecordVoice"
        @touchend="stopRecordVoice"
        @touchcancel="cancelRecordVoice"
      >
        {{ isRecording ? '松开发送' : '按住说话' }}
      </view>
      
      <!-- 表情按钮 -->
      <view class="emoji-btn" @click="toggleEmojiPanel">
        <tn-icon name="emoji" size="32" color="#666666"></tn-icon>
      </view>
      
      <!-- 更多功能按钮 -->
      <view class="more-btn" @click="toggleMorePanel">
        <tn-icon name="add" size="32" color="#666666"></tn-icon>
      </view>
    </view>
    
    <!-- 表情面板 -->
    <view class="emoji-panel" v-if="showEmojiPanel">
      <!-- 表情列表，实际项目中可以替换为更完整的表情包组件 -->
      <view class="emoji-list">
        <view 
          class="emoji-item" 
          v-for="(emoji, index) in emojiList" 
          :key="index"
          @click="insertEmoji(emoji)"
        >
          {{ emoji }}
        </view>
      </view>
    </view>
    
    <!-- 更多功能面板 -->
    <view class="more-panel" v-if="showMorePanel">
      <view class="panel-item" @click="chooseImage">
        <view class="panel-icon image-icon">
          <tn-icon name="image" size="36" color="#ffffff"></tn-icon>
        </view>
        <text>图片</text>
      </view>
      <view class="panel-item" @click="takePhoto">
        <view class="panel-icon camera-icon">
          <tn-icon name="camera" size="36" color="#ffffff"></tn-icon>
        </view>
        <text>拍照</text>
      </view>
    </view>
    
    <!-- 录音中提示 -->
    <view class="recording-popup" v-if="isRecording">
      <view class="recording-inner">
        <view class="recording-icon">
          <tn-icon name="voice" size="48" color="#32C5FF"></tn-icon>
        </view>
        <text>松开发送，上滑取消</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue';
import NavBar from '@/components/navbar/NavBar.vue';

// 聊天对象信息
const chatUser = ref({
  userId: '',
  userName: '',
  userAvatar: 'https://picsum.photos/id/1025/100/100'
});

// 消息列表
const messages = ref([]);
const hasMoreMessages = ref(false);
const isRefreshing = ref(false);
const scrollToMessageId = ref('');

// 输入相关
const inputText = ref('');
const isTextMode = ref(true);
const isRecording = ref(false);
const showEmojiPanel = ref(false);
const showMorePanel = ref(false);

// 简单的表情列表
const emojiList = ['😀', '😂', '😊', '😍', '😎', '🙄', '😏', '😢', '😭', '😡', '👍', '👎', '❤️', '💔'];

// 切换输入模式
const switchInputMode = () => {
  isTextMode.value = !isTextMode.value;
  showEmojiPanel.value = false;
  showMorePanel.value = false;
};

// 切换表情面板
const toggleEmojiPanel = () => {
  showEmojiPanel.value = !showEmojiPanel.value;
  showMorePanel.value = false;
};

// 切换更多功能面板
const toggleMorePanel = () => {
  showMorePanel.value = !showMorePanel.value;
  showEmojiPanel.value = false;
};

// 插入表情
const insertEmoji = (emoji) => {
  inputText.value += emoji;
};

// 发送文本消息
const sendTextMessage = () => {
  if (!inputText.value.trim()) return;
  
  const newMessage = {
    id: Date.now(),
    content: inputText.value,
    contentType: 'text',
    createTime: new Date(),
    isSelf: true,
    userAvatar: 'https://picsum.photos/id/1005/100/100',
    status: 'sending'
  };
  
  // 添加消息到列表
  messages.value.push(newMessage);
  
  // 清空输入框
  inputText.value = '';
  
  // 滚动到底部
  scrollToBottom();
  
  // 模拟发送成功
  setTimeout(() => {
    const index = messages.value.findIndex(msg => msg.id === newMessage.id);
    if (index !== -1) {
      messages.value[index].status = 'success';
    }
    
    // 模拟接收回复
    setTimeout(() => {
      const replyMessage = {
        id: Date.now(),
        content: '好的，收到了！',
        contentType: 'text',
        createTime: new Date(),
        isSelf: false,
        userAvatar: chatUser.value.userAvatar,
        status: 'success'
      };
      messages.value.push(replyMessage);
      scrollToBottom();
    }, 1000);
    
  }, 500);
};

// 重新发送消息
const resendMessage = (message) => {
  const index = messages.value.findIndex(msg => msg.id === message.id);
  if (index !== -1) {
    messages.value[index].status = 'sending';
    
    // 模拟重发
    setTimeout(() => {
      messages.value[index].status = 'success';
    }, 500);
  }
};

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];
      
      // 发送图片消息
      const newMessage = {
        id: Date.now(),
        content: tempFilePath,
        contentType: 'image',
        createTime: new Date(),
        isSelf: true,
        userAvatar: 'https://picsum.photos/id/1005/100/100',
        status: 'sending'
      };
      
      messages.value.push(newMessage);
      scrollToBottom();
      showMorePanel.value = false;
      
      // 模拟发送成功
      setTimeout(() => {
        const index = messages.value.findIndex(msg => msg.id === newMessage.id);
        if (index !== -1) {
          messages.value[index].status = 'success';
        }
      }, 500);
    }
  });
};

// 拍照
const takePhoto = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ['camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];
      
      // 发送图片消息
      const newMessage = {
        id: Date.now(),
        content: tempFilePath,
        contentType: 'image',
        createTime: new Date(),
        isSelf: true,
        userAvatar: 'https://picsum.photos/id/1005/100/100',
        status: 'sending'
      };
      
      messages.value.push(newMessage);
      scrollToBottom();
      showMorePanel.value = false;
      
      // 模拟发送成功
      setTimeout(() => {
        const index = messages.value.findIndex(msg => msg.id === newMessage.id);
        if (index !== -1) {
          messages.value[index].status = 'success';
        }
      }, 500);
    }
  });
};

// 开始录音
const startRecordVoice = () => {
  isRecording.value = true;
  console.log('开始录音');
  // 实际项目中应该调用录音API
};

// 结束录音
const stopRecordVoice = () => {
  if (!isRecording.value) return;
  
  isRecording.value = false;
  console.log('结束录音');
  
  // 实际项目中应该获取录音文件和时长
  // 模拟发送语音消息
  const newMessage = {
    id: Date.now(),
    content: 'audio://dummy-path',
    contentType: 'audio',
    duration: '3"',
    createTime: new Date(),
    isSelf: true,
    userAvatar: 'https://picsum.photos/id/1005/100/100',
    status: 'sending'
  };
  
  messages.value.push(newMessage);
  scrollToBottom();
  
  // 模拟发送成功
  setTimeout(() => {
    const index = messages.value.findIndex(msg => msg.id === newMessage.id);
    if (index !== -1) {
      messages.value[index].status = 'success';
    }
  }, 500);
};

// 取消录音
const cancelRecordVoice = () => {
  isRecording.value = false;
  console.log('取消录音');
};

// 播放语音
const playAudio = (audioPath) => {
  console.log('播放语音:', audioPath);
  // 实际项目中应该调用播放API
};

// 预览图片
const previewImage = (imagePath) => {
  uni.previewImage({
    urls: [imagePath]
  });
};

// 判断是否显示日期分隔线
const shouldShowDateDivider = (message, index) => {
  if (index === 0) return true;
  
  const currentDate = new Date(message.createTime);
  const prevDate = new Date(messages.value[index - 1].createTime);
  
  // 如果与前一条消息的时间相差超过30分钟，则显示日期分隔线
  return currentDate.getTime() - prevDate.getTime() > 30 * 60 * 1000;
};

// 格式化消息日期
const formatMessageDate = (date) => {
  const messageDate = new Date(date);
  const now = new Date();
  
  // 今天的消息只显示时间
  if (messageDate.toDateString() === now.toDateString()) {
    return messageDate.getHours().toString().padStart(2, '0') + ':' + 
           messageDate.getMinutes().toString().padStart(2, '0');
  }
  
  // 昨天的消息显示"昨天 + 时间"
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  if (messageDate.toDateString() === yesterday.toDateString()) {
    return '昨天 ' + messageDate.getHours().toString().padStart(2, '0') + ':' + 
           messageDate.getMinutes().toString().padStart(2, '0');
  }
  
  // 更早的消息显示完整日期
  return messageDate.getFullYear() + '-' + 
         (messageDate.getMonth() + 1).toString().padStart(2, '0') + '-' + 
         messageDate.getDate().toString().padStart(2, '0') + ' ' + 
         messageDate.getHours().toString().padStart(2, '0') + ':' + 
         messageDate.getMinutes().toString().padStart(2, '0');
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messages.value.length > 0) {
      const lastMessage = messages.value[messages.value.length - 1];
      scrollToMessageId.value = lastMessage.id;
    }
  });
};

// 加载更多消息
const loadMoreMessages = () => {
  if (hasMoreMessages.value) {
    console.log('加载更多历史消息');
    // 实际项目中应该调用API加载更多历史消息
  }
};

// 下拉刷新
const onRefresh = () => {
  isRefreshing.value = true;
  
  // 实际项目中应该调用API加载更多历史消息
  console.log('下拉刷新，加载更多历史消息');
  
  // 模拟加载完成
  setTimeout(() => {
    isRefreshing.value = false;
  }, 1000);
};

// 初始化聊天历史
const initChatHistory = () => {
  // 模拟历史消息
  const historyMessages = [
    {
      id: 1,
      content: '你好，我想咨询一下你发布的闲置物品还在吗？',
      contentType: 'text',
      createTime: new Date(new Date().getTime() - 3600000), // 1小时前
      isSelf: true,
      userAvatar: 'https://picsum.photos/id/1005/100/100',
      status: 'success'
    },
    {
      id: 2,
      content: '你好，还在的，有什么问题吗？',
      contentType: 'text',
      createTime: new Date(new Date().getTime() - 3550000), // 59分钟前
      isSelf: false,
      userAvatar: chatUser.value.userAvatar,
      status: 'success'
    },
    {
      id: 3,
      content: '价格可以便宜一点吗？',
      contentType: 'text',
      createTime: new Date(new Date().getTime() - 3500000), // 58分钟前
      isSelf: true,
      userAvatar: 'https://picsum.photos/id/1005/100/100',
      status: 'success'
    },
    {
      id: 4,
      content: '抱歉，价格已经很低了，不能再便宜了',
      contentType: 'text',
      createTime: new Date(new Date().getTime() - 1800000), // 30分钟前
      isSelf: false,
      userAvatar: chatUser.value.userAvatar,
      status: 'success'
    }
  ];
  
  messages.value = historyMessages;
  scrollToBottom();
};

onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.$page.options;
  
  if (options.userId) {
    chatUser.value.userId = options.userId;
  }
  
  if (options.userName) {
    chatUser.value.userName = decodeURIComponent(options.userName);
  }
  
  if (options.userAvatar) {
    chatUser.value.userAvatar = decodeURIComponent(options.userAvatar);
  }
  
  // 初始化历史消息
  initChatHistory();
});
</script>

<style lang="scss" scoped>
.chat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f1f1f1;
}

.chat-container {
  flex: 1;
  padding: 20rpx;
  box-sizing: border-box;
}

.loading-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 0;
  
  text {
    font-size: 24rpx;
    color: #999999;
    margin-left: 10rpx;
  }
}

.messages {
  padding-bottom: 20rpx;
}

.date-divider {
  display: flex;
  justify-content: center;
  margin: 30rpx 0;
  
  text {
    background-color: rgba(0, 0, 0, 0.1);
    padding: 6rpx 20rpx;
    border-radius: 20rpx;
    font-size: 24rpx;
    color: #666666;
  }
}

.message-item {
  display: flex;
  margin-bottom: 30rpx;
  
  &.message-self {
    flex-direction: row-reverse;
  }
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #e0e0e0;
  margin-right: 20rpx;
  
  &.self-avatar {
    margin-right: 0;
    margin-left: 20rpx;
  }
}

.message-content {
  max-width: 70%;
  
  &.self-content {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
  }
}

.message-bubble {
  padding: 20rpx;
  border-radius: 10rpx;
  background-color: #ffffff;
  word-break: break-all;
  
  &.self-bubble {
    background: linear-gradient(135deg, #32C5FF, #BA68C8);
    color: #ffffff;
  }
}

.image-message {
  max-width: 400rpx;
  border-radius: 10rpx;
  overflow: hidden;
  
  .message-image {
    width: 100%;
    height: auto;
    display: block;
    background-color: #e0e0e0;
  }
}

.audio-message {
  display: flex;
  align-items: center;
  padding: 16rpx 20rpx;
  border-radius: 10rpx;
  background-color: #ffffff;
  min-width: 160rpx;
  
  &.self-audio {
    background: linear-gradient(135deg, #32C5FF, #BA68C8);
    
    text {
      color: #ffffff;
    }
  }
  
  text {
    margin-left: 10rpx;
    font-size: 28rpx;
    color: #666666;
  }
}

.message-status {
  margin-top: 6rpx;
}

.input-area {
  background-color: #ffffff;
  border-top: 1px solid #f0f0f0;
  padding: 20rpx;
  display: flex;
  align-items: center;
}

.toggle-btn,
.emoji-btn,
.more-btn {
  padding: 0 10rpx;
}

.text-input {
  flex: 1;
  height: 70rpx;
  background-color: #f5f5f5;
  border-radius: 35rpx;
  padding: 0 20rpx;
  margin: 0 10rpx;
  font-size: 28rpx;
}

.voice-input {
  flex: 1;
  height: 70rpx;
  background-color: #f5f5f5;
  border-radius: 35rpx;
  margin: 0 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  color: #666666;
}

.emoji-panel,
.more-panel {
  height: 500rpx;
  background-color: #ffffff;
  border-top: 1px solid #f0f0f0;
  padding: 20rpx;
}

.emoji-list {
  display: flex;
  flex-wrap: wrap;
  
  .emoji-item {
    width: 70rpx;
    height: 70rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 40rpx;
  }
}

.more-panel {
  display: flex;
  flex-wrap: wrap;
  
  .panel-item {
    width: 20%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 30rpx;
    
    .panel-icon {
      width: 100rpx;
      height: 100rpx;
      border-radius: 20rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 10rpx;
    }
    
    .image-icon {
      background-color: #32C5FF;
    }
    
    .camera-icon {
      background-color: #76FF03;
    }
    
    text {
      font-size: 24rpx;
      color: #666666;
    }
  }
}

.recording-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  
  .recording-inner {
    background-color: #ffffff;
    width: 300rpx;
    height: 300rpx;
    border-radius: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    
    .recording-icon {
      margin-bottom: 30rpx;
    }
    
    text {
      font-size: 26rpx;
      color: #999999;
    }
  }
}
</style> 